package com.zhongwang.mms.module.buy.service;

import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.gen.mapper.BShoppingPlanImportLogMapper;
import com.zhongwang.mms.gen.mapper.BShoppingPlanMapper;
import com.zhongwang.mms.module.basic.dao.TCostDao;
import com.zhongwang.mms.module.buy.dao.BuyPlanDao;
import com.zhongwang.mms.module.buy.model.*;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ExcelUtils;
import com.zhongwang.mms.util.FileUtils;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 采购计划导出 Service
 * @Author: China.sgl
 * @Date: 2020/4/7 16:25
 */
@SuppressWarnings("ALL")
@Service
@Log4j2
public class ExportBuyPlanService {

    @Autowired
    private LogService logService;
    @Autowired
    private BuyPlanDao buyPlanDao;
    @Autowired
    private BShoppingPlanMapper bShoppingPlanMapper;
    @Autowired
    private BShoppingPlanImportLogMapper bShoppingPlanImportLogMapper;
    @Autowired
    private TCostDao tCostDao;
    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * 查询仓库字典表
     *
     * @return list
     */
    public List<TWarehouseInfo> findStocks() {
        return buyPlanDao.findStocks();
    }

    /**
     * 按条件查询提报计划
     *
     * @param shoppingPlanModel 条件
     * @return list
     */
    public List<ShoppingPlanModel> findBuyPlanByQuery(ShoppingPlanModel shoppingPlanModel) {
        if(!ShiroUtils.getUser().getAccount().equals("admin")){
            shoppingPlanModel.setSppPlanner(ShiroUtils.getUser().getName());
        }
        if (shoppingPlanModel.getSppProjectCodeArrayStr() != null && !shoppingPlanModel.getSppProjectCodeArrayStr().equals("")) {
            String[] strArray = shoppingPlanModel.getSppProjectCodeArrayStr().split(",");
            shoppingPlanModel.setSppProjectCodeArray(Arrays.asList(strArray));
        }
        return buyPlanDao.findExportBuyPlanByQuery(shoppingPlanModel);
    }


    /**
     * 采购计划导出 撤消功能， 同时撤消导出的一批数据
     *
     * @param id 主键
     * @return 行数
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancel(Integer id) {
        BShoppingPlan plan = bShoppingPlanMapper.selectByPrimaryKey(id);
        logService.saveLog("撤消采购计划导出", "批量撤消采购计划导出");
        buyPlanDao.updateBuyPlanStatusAndClearExportLogIdBySpiId(plan.getSppImportLogId());
        return buyPlanDao.updateSpiStatus(plan.getSppImportLogId());
    }

    /**
     * 采购计划导出 撤消功能， 单条撤销
     *
     * @param id 主键
     * @return 行数
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancelSingle(Integer id) {
        BShoppingPlan plan = new BShoppingPlan();
        plan.setSppId(id);
        logService.saveLog("撤消采购计划导出", "单条撤消采购计划导出");
        return buyPlanDao.updateBuyPlanStatusAndClearExportLogIdBySppId(plan);
    }

    /**
     * 采购计划导出
     *
     * @param ids
     * @param remark
     * @param response
     */
    //@Transactional(rollbackFor = Exception.class)
    public void export(String ids, String remark, HttpServletResponse response) {
        List<ExportBuyPlanModel> list = buyPlanDao.findBuyPlanMayExportList(ids);
        for (ExportBuyPlanModel model : list) {
            if (null == tCostDao.getTCostByCosProCode(model.getSppProjectCode())) {
                String beginStr = model.getSppProjectCode().trim().toCharArray()[0] + "" + model.getSppProjectCode().trim().toCharArray()[1];
                char lastChar = model.getSppProjectCode().trim().toCharArray()[model.getSppProjectCode().trim().length() - 1];
                if (!beginStr.toUpperCase().equals("ZW")
                        && !isNumeric(model.getSppProjectCode().trim())
                        && !(lastChar >= 'a' && lastChar <= 'z')
                        && !(lastChar >= 'A' && lastChar <= 'Z')) {
                    String handleCode = model.getSppProjectCode().trim().substring(2);
                    model.setSppProjectCode(handleCode);
                }
            }
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        logService.saveLog("采购计划导出列表——采购计划导出","用户:【"+user.getName()+"】执行采购计划导出操作！");
        String path = uploadPath + user.getAccount() + "/";
        List<String> comments = new ArrayList<>();
        comments.add("seqnum|onetext|");
        comments.add("wlbh|sapSelector|");
        comments.add("wlms|onetext|");
        comments.add("ywy|select|{'choiceType':'enum_dic','source':'159acdf967954f3baa40190b10722474','required':''}");
        comments.add("ywylxfs|select|{'choiceType':'enum_dic','source':'','selectbind':'ywy','required':'true'}");
        comments.add("jhzq|onetext|");
        comments.add("cgsl|onetext|");
        comments.add("kcsl|onetext|");
        comments.add("fkcsl|onetext|");
        comments.add("fjkcsl|onetext|");
        comments.add("dwdm|onetext|");
        comments.add("dwwb|onetext|");
        comments.add("kw|onetext|");
        comments.add("cgz|onetext|");
        comments.add("wlz|onetext|");
        comments.add("bzjhyt|multitext|");
        comments.add("syzq|onetext|");
        comments.add("pp|onetext|");
        comments.add("sgdw|onetext|");

        ExcelUtils.export(path, "采购计划OA模板.xls", ExportBuyPlanModel.class, "sheet1", list, comments,  response);
        BShoppingPlanImportLog log = new BShoppingPlanImportLog();
        log.setSpiTrackCode(genImportBatchCode());
        log.setSpiCreateTime(new Date());
        log.setSpiCreateUser(user.getName());
        log.setSpiEnableFlag(1);
        log.setSpiStatus(1);
        log.setSpiType(1);
        log.setSpiRemark(remark);
        bShoppingPlanImportLogMapper.insert(log);
        buyPlanDao.updateBuyPlanStatusAndExportLogId(log.getSpiId(), ids);
        logService.saveLog("采购计划导出", "采购计划导出");
    }

    /**
     * 采购计划导出附表
     *
     * @param ids
     * @param remark
     * @param response
     */
    //@Transactional(rollbackFor = Exception.class)
    public void exportSchedule(String ids, String remark, HttpServletResponse response) {
        List<ExportBuyPlanScheduleModel> list = buyPlanDao.findBuyPlanScheduleMayExportList(ids);
        for (ExportBuyPlanScheduleModel model : list) {
            if (null == tCostDao.getTCostByCosProCode(model.getRppProjectCode())) {
                String beginStr = model.getRppProjectCode().trim().toCharArray()[0] + "" + model.getRppProjectCode().trim().toCharArray()[1];
                char lastChar = model.getRppProjectCode().trim().toCharArray()[model.getRppProjectCode().trim().length() - 1];
                if (!beginStr.toUpperCase().equals("ZW")
                        && !isNumeric(model.getRppProjectCode().trim())
                        && !(lastChar >= 'a' && lastChar <= 'z')
                        && !(lastChar >= 'A' && lastChar <= 'Z')) {
                    String handleCode = model.getRppProjectCode().trim().substring(2);
                    model.setRppProjectCode(handleCode);
                }
            }
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        logService.saveLog("采购计划导出列表——采购计划附表导出","用户:【"+user.getName()+"】执行采购计划附表导出操作！");
        String path = uploadPath + user.getAccount() + "/";
        FileUtils.export(path, "采购计划OA附表模板.xls", ExportBuyPlanScheduleModel.class, "sheet1", list, response);
//        BShoppingPlanImportLog log = new BShoppingPlanImportLog();
//        log.setSpiCreateTime(new Date());
//        log.setSpiCreateUser(user.getName());
//        log.setSpiEnableFlag(1);
//        log.setSpiStatus(1);
//        log.setSpiType(1);
//        log.setSpiRemark(remark);
//        bShoppingPlanImportLogMapper.insert(log);
//        buyPlanDao.updateBuyPlanStatusAndExportLogId(log.getSpiId(), ids);
        logService.saveLog("采购计划附表导出", "采购计划附表导出");
    }

    /**
     * 按条件查询采购计划变更记录表数据
     *
     * @param shoppingPlanModel 条件
     * @return list
     */
    public List<BShoppingPlanChange> findBuyPlanChangeLogByQuery(ShoppingPlanModel shoppingPlanModel) {
        shoppingPlanModel.setSppPlanner(ShiroUtils.getUser().getName());
        return buyPlanDao.findBuyPlanChangeLogByQuery(shoppingPlanModel);
    }

    /**
     * 删除变更记录
     *
     * @param id 主键
     * @return 行数
     */
    public int delChangeBuyPlanById(Integer id) {
        return buyPlanDao.updateBuyPlanChangeLogStatusById(id);
    }

    /**
     * @FunctionName: genImportBatchCode
     * @Description: 生成导入批次号
     * @DesignIdea: 生成一个用来检索一个批次导入的数据检索依赖字段数据
     * @Author: 徐一贺
     * @CreateDate: 2020/6/9 8:28
     * @Phone: 18241927380
     * @Return: [code] 生成的批次码
     * @Throw: [Exception] 抛出SQL异常与字符串控制异常
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    private String genImportBatchCode() {
        String code = "";
        try {
            //验证数据库中是否有该批次号没有的话返回
            boolean isLoop = true;
            while (isLoop) {
                //生成公式 SPC + 年后两位+月+日+6位随机数
                code = "SPC" + new SimpleDateFormat("YYMMdd").format(new Date()) + ((int) ((Math.random() * 9 + 1) * 100000));
                BShoppingPlanImportLog log = buyPlanDao.selectBySpiTrackCode(code);
                isLoop = !(log == null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            code = "";
        }
        return code;
    }

    /**
     * @FunctionName: isNumeric
     * @Description: 用Ascii码验证字符串是否为全数字
     * @DesignIdea: 用Ascii码验证字符串是否为全数字
     * @Author: 徐一贺
     * @CreateDate: 2020/6/1 11:25
     * @Phone: 18241927380
     * @Param: [str] 验证字符串
     * @Version: v 1.0.0
     */
    public boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            int chr = str.charAt(i);
            if (chr < 48 || chr > 57)
                return false;
        }
        return true;
    }

    /**
     * 导出变更记录
     *
     * @param ids      主键字符串
     * @param remark   备注
     * @param response
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeExport(String ids, String remark, HttpServletResponse response) {
        List<ExportBuyPlanChnageModel> list = buyPlanDao.findBuyPlanChangeLogMayExportList(ids);
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        logService.saveLog("采购计划导出列表——导出变更记录","用户:【"+user.getName()+"】执行导出变更记录操作！");
        String path = uploadPath + user.getAccount() + "/";
        List<String> comments = new ArrayList<>();
        comments.add("seqnum|onetext|");
        comments.add("xqgzh|onetext|");
        comments.add("jhrq|date|");
        comments.add("wlbm|sapSelector|");
        comments.add("wlms|onetext|");
        comments.add("ggqsl|onetext|");
        comments.add("gghsl|onetext|");
        comments.add("cgywy|select|{'choiceType':'enum_dic','source':'159acdf967954f3baa40190b10722474','required':''}");
        comments.add("sfsc|checkbox|{'choiceType':'static','source':'[{\\'name\\':\\'是否删除\\',\\'code\\':\\'是否删除\\'}]','required':''}");
        ExcelUtils.export(path, "采购计划变更模板.xls", ExportBuyPlanChnageModel.class, "sheet1", list, comments, response);
        BShoppingPlanImportLog log = new BShoppingPlanImportLog();
        log.setSpiTrackCode(genImportBatchCode());
        log.setSpiCreateTime(new Date());
        log.setSpiCreateUser(user.getName());
        log.setSpiEnableFlag(1);
        log.setSpiStatus(1);
        log.setSpiType(2);
        log.setSpiRemark(remark);
        bShoppingPlanImportLogMapper.insert(log);
        buyPlanDao.updateBuyPlanChangeLogStatusAndExportId(log.getSpiId(), ids);
    }

    /**
     * 采购计划变更附表导出
     *
     * @param ids 主键集合
     * @param response 输出流
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeExportSchedule(String ids, HttpServletResponse response) {
        List<ExportBuyPlanChangeScheduleModel> list = buyPlanDao.findBuyplanChangeLogMayExportSubList(ids);
        String path = uploadPath + ShiroUtils.getLoginName() + "/";
        FileUtils.export(path, "采购计划变更OA附表模板.xls", ExportBuyPlanChangeScheduleModel.class, "sheet1", list, response);
        logService.saveLog("采购计划导出列表——采购计划变更附表导出", "采购计划变更附表导出");
    }
}
